package com.sjt.demo5;

import java.util.Random;

public class PhilosopherQuestion {


    public static void main(String[] args) {
        Philosopher philosopher1=new Philosopher(0);
        Philosopher philosopher2=new Philosopher(1);
        Philosopher philosopher3=new Philosopher(2);
        Philosopher philosopher4=new Philosopher(3);
        Philosopher philosopher5=new Philosopher(4);
        new Thread(philosopher1).start();
        new Thread(philosopher2).start();
        new Thread(philosopher3).start();
        new Thread(philosopher4).start();
        new Thread(philosopher5).start();
    }
}
class Philosopher implements Runnable{
    //初始化所有筷子
    public static Object[] chopstick=new Object[]{0,0,0,0,0};
    //哲学家编号
    public int num;
    //拿筷子的两个方向
    private int dir1,dir2;

    public Philosopher(int num) {
        this.num = num;
    }

    @Override
    public void run() {
           while(true) {
               System.out.println("哲学家" + this.num + "正在思考ing......");
               try {
                   Thread.sleep(2000);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
               rand_dir(this.num);
               synchronized (chopstick[dir1]) {
                   if (chopstick[dir1].equals(0)) {
                       chopstick[dir1] = 1;
                       synchronized (chopstick[dir2]) {
                           if (chopstick[dir2].equals(0)) {
                               chopstick[dir2] = 1;
                               System.out.println("哲学家" + this.num + "正在吃饭ing......");
                               try {
                                   Thread.sleep(1000);
                               } catch (InterruptedException e) {
                                   e.printStackTrace();
                               }
                           }
                           chopstick[dir2] = 0;
                       }
                   }
                   chopstick[dir1] = 0;
               }
           }
    }

    //随机拿筷子的方向
    public void rand_dir(int num)
    {
        Random r = new Random();
        int number = r.nextInt(2);
        if(number==0)
        {
            dir1=num;
            dir2=(num+1)%5;
        }else{
            dir1=(num+1)%5;
            dir2=num;
        }
    }
}